
type fnType = () => void;
export type actionType<T> = {
  type: string;
  payload: T;
};
export type reducerType<T> = (state: T, action: actionType<T>) => T;
//返回值
type createDataReturn<T> = {
  subscribe: (fn: fnType) => void;
  changeData: (value: T) => void;
  getData: () => T;
  setDataByAction: (action: actionType<T>) => void;
};
export const createData = function <T>(
  installData: T,
  reducer: reducerType<T>
): createDataReturn<T> {
  let data: T = installData;
  const dep: fnType[] = [];
  //订阅者
  function subscribe(fn: fnType) {
    dep.push(fn);
  }
  //修改数据
  function changeData(value: T) {
    data = value;
    console.log(value, "----cvvv");

    if (dep.length > 0) {
      dep.forEach((fn) => fn());
    }
  }
  //用reducer 修改数据
  function setDataByAction(action: actionType<T>) {
    const state = reducer(data, action);
    data = state;
    if (dep.length > 0) {
      dep.forEach((fn) => fn());
    }
  }
  //获取数据
  function getData(): T {
    return data;
  }
  return {
    subscribe,
    changeData,
    getData,
    setDataByAction,
  };
};
